import * as Koa from 'koa';
import { searchPicture, updatePicture } from '../entity/picture';
const dayjs = require("dayjs");
// TODO：commonjs 模式下引用 esmodule 模块
let nanoid: any = null;
(async () => {
  nanoid = (await eval("import('nanoid')")).nanoid;
})();

const errorMsg = `服务器错误：${'banner'}`;
const successMsg = `成功：${'banner'}`;

export default class BannerService {
  /**
   * 设置图片为banner
   * @param ctx 
   * @returns 
   */
  addBanner = async (ctx: Koa.Context) => {
    try {
      const { pid } = ctx.request.body;
      if (!pid || !pid.length) return ctx.fail(null, "pid不能为空", -1);
      const pids = Array.isArray(pid)? pid : [pid];
      if (!pids?.length) return ctx.fail(null, '请传入指定图片ID', -1);
      const picture = {
        is_banner: "1",
        update_time: dayjs().format("YYYY-MM-DD HH:mm:ss"), // 最后的更新时间
      };
      const errorItems = [];
      for (const _id of pids) {
        const result: any = picture && (await updatePicture(ctx, Object.assign(picture, { pid: _id })));
        if (!result?.success) {
          errorItems.push(_id);
        }
      }
      if (!!errorItems.length) {
        ctx.fail(null, errorMsg, -1);
      } else {
        ctx.success(null, '成功');
      }
    } catch (error) {
      ctx.fail(null, errorMsg, -1);
    }
  };

  /**
   * 删除
   * @param ctx 
   */
  delBanner = async (ctx: Koa.Context) => {
    try {
      const { pid } = ctx.request.body;
      if (!pid || !pid.length) return ctx.fail(null, "pid不能为空", -1);
      const pids = Array.isArray(pid)? pid : [pid];
      if (!pids?.length) return ctx.fail(null, '请传入指定图片ID', -1);
      const picture = {
        is_banner: "0",
        update_time: dayjs().format("YYYY-MM-DD HH:mm:ss"), // 最后的更新时间
      };
      const errorItems = [];
      for (const _id of pids) {
        const result: any = picture && (await updatePicture(ctx, Object.assign(picture, { pid: _id })));
        if (!result?.success) {
          errorItems.push(_id);
        }
      }
      if (!!errorItems.length) {
        ctx.fail(null, errorMsg, -1);
      } else {
        ctx.success(null, '成功');
      }
    } catch (error) {
      ctx.fail(null, errorMsg, -1);
    }
  };

  /**
   * 查询
   * @param ctx 
   */
  searchBanner = async (ctx: Koa.Context) => {
    try {
      let condition = `WHERE is_show = "1" AND is_origin = "0" AND is_banner = "1"`;
      const result: any = await searchPicture(ctx, { condition });
      if (!result) {
        ctx.fail(null, result.msg || errorMsg, -1);
      } else if (!result.success) {
        ctx.fail(null, result.msg || errorMsg, -1);
      } else {
        ctx.success({
          list: result.data || [],
        }, successMsg);
      }
    } catch (error) {
      ctx.fail(null, error, -1);
    }
  };
}
